/**
 * www.ewanse.com.
 * Copyright (c) 2009-2016 All Rights Reserved.
 */
package com.sunday.bo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.sunday.dao.GoodsCateGoryDOMapper;
import com.sunday.pojo.GoodsCateGoryDO;

/**
 * 商品分类BO
 * @author donghongli
 * @version $Id: GoodsCateGoryBO.java, v 0.1 2016年1月6日 下午6:06:16 donghongli Exp $
 */
@Service
public class GoodsCateGoryBO {

    @Autowired
    private GoodsCateGoryDOMapper         goodsCateGoryDOMapper;

    //分类缓存
    private Map<Integer, GoodsCateGoryDO> cats = new HashMap<Integer, GoodsCateGoryDO>();

    private List<GoodsCateGoryDO> queryByDB() {
        return goodsCateGoryDOMapper.list();
    }

    public List<GoodsCateGoryDO> list() {
        checkAndInitGoodsCats();
        List<GoodsCateGoryDO> catList = new ArrayList<GoodsCateGoryDO>();
        for (Integer catId : cats.keySet()) {
            catList.add(cats.get(catId));
        }
        return catList;
    }

    public GoodsCateGoryDO getById(Integer catId) {
        if (catId == null)
            return null;
        checkAndInitGoodsCats();
        return cats.get(catId);
    }

    private void checkAndInitGoodsCats() {
        if (!CollectionUtils.isEmpty(cats)) {
            return;
        }
        initGoodsCats();
    }

    private void initGoodsCats() {
        cats.clear();
        List<GoodsCateGoryDO> catList = queryByDB();
        for (GoodsCateGoryDO goodsCateGoryDO : catList) {
            cats.put(goodsCateGoryDO.getId(), goodsCateGoryDO);
        }
    }

}
